package com.sgb.kjwl.view.ui.fragment.home;

import static com.swgk.core.event.EventConstant.EVENT_BIG_HOME_VIDEO;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.apeng.permissions.EsayPermissions;
import com.apeng.permissions.OnPermission;
import com.chuanglan.shanyan_sdk.OneKeyLoginManager;
import com.chuanglan.shanyan_sdk.listener.OneKeyLoginListener;
import com.chuanglan.shanyan_sdk.listener.OpenLoginAuthListener;
import com.sgb.kjwl.AppFragment;
import com.sgb.kjwl.BR;
import com.sgb.kjwl.R;
import com.sgb.kjwl.api.GsonManager;
import com.sgb.kjwl.databinding.FragmentHomeChildBinding;
import com.sgb.kjwl.di.home.DaggerHomeFragComponent;
import com.sgb.kjwl.di.home.HomeFragModule;
import com.sgb.kjwl.model.entity.LoginEntity;
import com.sgb.kjwl.model.entity.UserMsgEntity;
import com.sgb.kjwl.model.entity.user.OneKeyLoginEntity;
import com.sgb.kjwl.utils.ConfigUtils;
import com.sgb.kjwl.view.event.LoginEvent;
import com.sgb.kjwl.view.ui.activity.WebViewX5HostActivity;
import com.sgb.kjwl.view.ui.activity.self.userInfo.VerificationCodeLoginActivity;
import com.sgb.kjwl.viewmodel.home.BigHomeVideoFragModel;
import com.sgb.knowledgeshare.view.activity.PlayListActivity;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.base.model.entity.VideoBean;
import com.swgk.core.dialog.DialogHelper;
import com.swgk.core.event.EventConstant;
import com.swgk.core.event.MenuEvent;
import com.swgk.core.mmkvutil.CacheMarker;
import com.swgk.core.mmkvutil.MkvUtils;
import com.swgk.core.recyclerview.adapter.AdapterOnItemClick;
import com.swgk.core.recyclerview.adapter.BaseRecycleAdapter;
import com.swgk.core.recyclerview.adapter.ItemViewHolder;
import com.swgk.core.util.ResolutionUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;


/**
 * Description:
 * Author CFK
 */
public class BigHomeVideoFragment extends AppFragment {
    public static final String TAG = "";
    public static final String KEY_TYPE = "type";
    private FragmentHomeChildBinding binding;
    //热门分享
    private HomeHostVideoAdapter bigHomeHostVideoAdapter;
    private String type = "";
    private String id = "";
    private boolean isCreate = false;
    private boolean isBind = false;
    private boolean init = true;
    private boolean isVisible;
    @Inject
    BigHomeVideoFragModel viewModel;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }
        isCreate = true;
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        isVisible = isVisibleToUser;
        if (!isCreate) {
            return;
        }
        if (isVisibleToUser) {
            if (init) {
                init = false;
                init();
            }
        }
    }

    @Override
    protected void setupFragmentComponent(AppComponent appComponent) {
        DaggerHomeFragComponent.builder()
                .appComponent(appComponent)
                .homeFragModule(new HomeFragModule(this))
                .build()
                .inject(this);
    }

    public static BigHomeVideoFragment newInstance(String type, String id) {
        BigHomeVideoFragment fragment = new BigHomeVideoFragment();
        Bundle bundle = new Bundle();
        bundle.putString(KEY_TYPE, type);
        bundle.putString("id", id);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_home_child, container, false);
        binding.setViewModel(viewModel);
        return binding.getRoot();
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        type = (String) getArguments().get(KEY_TYPE);
        id = (String) getArguments().get("id");
        initView();
        if (init && isVisible) {
            init = false;
            init();
        }
    }

    private void initView() {
        if (type != null) {
            if (bigHomeHostVideoAdapter == null) {
                bigHomeHostVideoAdapter = new HomeHostVideoAdapter(getActivity(), null, R.layout.item_big_host_video2);
            }
            binding.rlvOption3.setLayoutManager(new LinearLayoutManager(getActivity(), LinearLayoutManager.HORIZONTAL, false));
            binding.rlvOption3.setAdapter(bigHomeHostVideoAdapter);
            bigHomeHostVideoAdapter.setOnItemClick(new AdapterOnItemClick<VideoBean>() {
                @Override
                public void onItemClick(VideoBean homeHostVideoEntity, int position) {
                    Intent intent = new Intent(getActivity(), PlayListActivity.class);
                    intent.putExtra(PlayListActivity.VIDEOLISTBEAN,(Serializable) bigHomeHostVideoAdapter.getDatas());
                    intent.putExtra(PlayListActivity.PSO,position);
                    intent.putExtra(PlayListActivity.VIDEOTITLE,id+"");
                    intent.putExtra(PlayListActivity.VIDEOTYPE,"home_bigVideo");
                    getActivity().startActivity(intent);
                }
            });
        }
    }

    public class HomeHostVideoAdapter extends BaseRecycleAdapter<VideoBean> {

        public HomeHostVideoAdapter(Context context, List<VideoBean> datas, int layout) {
            super(context, layout, datas);
        }

        @Override
        public void convert(ItemViewHolder holder, final VideoBean entity) {
            holder.setBinding(BR.viewModel, entity);
            int width = ResolutionUtil.getScreenWidth(getActivity()) - ResolutionUtil.dp2px(getActivity(), 30);
            RelativeLayout relativeLayout = holder.itemView.findViewById(R.id.rel_layout);
            ViewGroup.LayoutParams layoutParams = relativeLayout.getLayoutParams();
            layoutParams.width = (width / 3) * 2;
            relativeLayout.setLayoutParams(layoutParams);

            TextView textView = holder.itemView.findViewById(R.id.tv_labelName);
            if (!TextUtils.isEmpty(entity.getTitle())){
                textView.setText(entity.getTitle());
            }else {
                textView.setText("");
            }
            String names = textView.getText().toString();
            if (!TextUtils.isEmpty(entity.getLabelName())){
                if (entity.getLabelName().length()>=7){
                    textView.setText("# "+entity.getLabelName().substring(0,6)+"...\n"+names);
                }else {
                    textView.setText("# "+entity.getLabelName()+" "+names);
                }
            }

        }
    }

    private void init() {
        viewModel.getVideoListByType(id);
    }


    public void showList5(List<VideoBean> list) {
        if (list.size() > 0) {
            bigHomeHostVideoAdapter.setDatas(list);
            binding.ntscrollView2.setVisibility(View.GONE);
            binding.empty2.setVisibility(View.GONE);
        } else {
            bigHomeHostVideoAdapter.setDatas(null);
            binding.ntscrollView2.setVisibility(View.VISIBLE);
            binding.empty2.setVisibility(View.VISIBLE);
        }
    }

    public void showUrl(String url) {
        WebViewX5HostActivity.start(getActivity(), url);
    }

    public void jumpLogin() {
        boolean shanyan = MkvUtils.get().getBoolean(MkvUtils.CommomData, CacheMarker.ShanYan, false);
        if (shanyan) {
            //校验权限
            //申请动态权限
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                //6.0以上运行时权限处理
                EsayPermissions.with(getActivity()).constantRequest().permission(PERMISSIONS).request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean isAll) {
                        openLoginPage();
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {
                        openLoginPage();
                    }
                });

            } else {
                //有权限
                openLoginPage();
            }

        } else {
            VerificationCodeLoginActivity.start(getActivity());
        }
    }

    //闪验
    static final String[] PERMISSIONS = new String[]{
            Manifest.permission.READ_PHONE_STATE
    };

    /**
     * 拉起授权页
     */
    private void openLoginPage() {
        //设置授权页样式
        OneKeyLoginManager.getInstance().setAuthThemeConfig(ConfigUtils.getCJSConfig(getActivity()));
        //开始拉取授权页
        DialogHelper.showProgressDialog(getActivity(), null, "数据加载中", 0, true, null).setCanceledOnTouchOutside(true);
        OneKeyLoginManager.getInstance().openLoginAuth(false, new OpenLoginAuthListener() {
            @Override
            public void getOpenLoginAuthStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code != 1000) {
                    VerificationCodeLoginActivity.start(getActivity());
                }
            }
        }, new OneKeyLoginListener() {
            @Override
            public void getOneKeyLoginStatus(int code, String result) {
                DialogHelper.dismissProgressDialog();
                if (code == 1000) {
                    OneKeyLoginEntity oneKeyLoginEntity = GsonManager.getInstance().getGson().fromJson(result, OneKeyLoginEntity.class);
                    oneKeyLoginEntity.setPlateform("Android");
                    viewModel.oneKeyLogin(oneKeyLoginEntity);
                }
            }
        });
    }

    /**
     * 一键登录成功
     *
     * @param loginEntity
     * @param phoneNumber
     */
    public void loginSucceed(LoginEntity loginEntity, String phoneNumber) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageData(phoneNumber);
        loginEvent.setMessageTag(EventConstant.EVENT_LOGIN);
        loginEvent.setObject(loginEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    public void getUserMsgSucceed(UserMsgEntity userMsgEntity) {
        LoginEvent loginEvent = new LoginEvent();
        loginEvent.setMessageTag(EventConstant.EVENT_USER_MSG);
        loginEvent.setMessageData(userMsgEntity);
        EventBus.getDefault().postSticky(loginEvent);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MenuEvent event) {
        if (event.getMessageTag() == EVENT_BIG_HOME_VIDEO) {
            viewModel.getVideoListByType(id);
        }
        //如果删除了前三个视频，就更新数据列表信息
        if (event.getMessageTag() == EventConstant.EVENT_HOME_PLAY_VIDEOLIST){
            init();
        }
    }
}
